#include "ShaderEffect.h"

ShaderEffect::ShaderEffect()
{
	effect = NULL;
	compile_errors = NULL;
	inEffect = false;
	mTexture = NULL;
}

ShaderEffect::~ShaderEffect()
{
	StopEffect();

	if( effect != NULL )
		effect->Release();

	effect = NULL;
}

void ShaderEffect::LoadEffect(LPDIRECT3DDEVICE9 d3ddev)
{
	/**
	Load Effect File
	*/
	
	if( FAILED (D3DXCreateEffectFromFile(d3ddev, "../../Shaders/SimpleTexShader.txt", NULL, NULL, NULL, NULL, &effect, &compile_errors) ) )
	{
		_cprintf("Failed to load shader!\n");
		_cprintf("%s\n", compile_errors->GetBufferPointer());
	}
	else
		_cprintf("Succeeded to load shader!\n");

}

void ShaderEffect::SetEffectTech(std::string param)
{
	/**
	Set Technique
	*/
	if( currentTechnique.compare(param) == 0);
	else
	{
		currentTechnique = param;
		Handle_tech = effect->GetTechniqueByName(param.c_str());
		effect->SetTechnique(Handle_tech);
	}
}

void ShaderEffect::SetEffectTex(std::string param, Texture * texture)
{
	/**
	Set texture
	*/

	bool same = 1;

	if( mTexture == NULL )
		mTexture = texture;

	if( mTexture != texture )
	{
		same = 0;
		mTexture = texture;
		Handle_tex = effect->GetParameterByName(0, param.c_str());
		effect->SetTexture( Handle_tex, texture->GetTexture() );
	}


}

void ShaderEffect::setTestParam(D3DXMATRIX M, std::string param)
{
	/**
	Set matrix
	*/
	Handle_gWVP = effect->GetParameterByName(0, param.c_str());
	effect->SetMatrix(Handle_gWVP, &M);
}


void ShaderEffect::UseEffect(int pass)
{
	if( inEffect == false )
	{
		UINT numpasses = 0;
		effect->Begin(&numpasses, 0 );
		effect->BeginPass(pass);
	}

	inEffect = true;
}

void ShaderEffect::StopEffect()
{
	if( inEffect == true )
	{
		effect->EndPass();
		effect->End();
	}

	inEffect = false;
}